﻿using Blog.Core.Entity;
using Blog.Core.Service;
using Nancy;
using Nancy.Extensions;
using Nancy.ModelBinding;
using System;

namespace Web.Module
{
    public class AdminPostsModule : AdminModule
    {
        private readonly PostService _postService = new PostService();
        public AdminPostsModule()
        {
            Get["/posts/add"] = p => { ViewBag.Categorys = PostCategory.Fetch(""); return View["addpost"]; };

            Post["/posts/add"] = _ =>
            {
                var model = this.Bind<Posts>();
                return AddPost(model);
            };

            Get["/posts/edit/{id}"] = p => EditPost(p.id);

            Post["/posts/edit"] = p =>
            {
                var model = this.Bind<Posts>();
                return EditPost(model);
            };

            Get["/posts/{page?1}"] = p => Posts(p.page, 0);

            Get["/posts/del/{id:int}"] = p => DelPost(p.id);

        }

        public dynamic Posts(int page, int categoryId)
        {
            var list = _postService.GetPostList(page, 5, categoryId);
            return View["posts", list];
        }

        public dynamic EditPost(int id)
        {
            var model = Blog.Core.Entity.Posts.SingleOrDefault(id);
            ViewBag.Categorys = PostCategory.Fetch("");
            return View["editpost", model];
        }

        public dynamic EditPost(Posts model)
        {
            model.Update();
            return Context.GetRedirect("/sean/posts");
        }

        public Response AddPost(Posts model)
        {
            model.CreateTime = DateTime.Now;
            model.Summary = "";
            model.Insert();
            return Context.GetRedirect("/sean/posts");

        }

        public dynamic DelPost(int id)
        {
            Blog.Core.Entity.Posts.repo.Execute("DELETE FROM [Post] WHERE Id=@0", id);
            return Context.GetRedirect("/sean/posts");
        }
    }
}